<template>
	<view class="detail-view">
		<view class="top-bar"><uni-navbar :fixed="true" :back="true" color="#fff" :title="title"></uni-navbar></view>

		<view class="form-box">
			<u-form :model="form" ref="uForm" :rules="rules">
				<!-- <u-form-item class="form-item" label="编号"><u-input v-model="form.no" type="text" placeholder="自动生成，可手动添加" /></u-form-item> -->
				<u-form-item class="form-item" required label="届次">{{ form.jieci }}</u-form-item>
				<u-form-item class="form-item" required label="标题" prop="title"><u-input v-model="form.title" type="text" placeholder="请输入标题" /></u-form-item>

				<!-- <uni-view class="title-tip">关于......的建议，标题仅需填写“......”的内容</uni-view> -->
				<!-- <u-form-item class="form-item" required label="类别" prop="type">
					<u-input v-model="type" type="select" :select-open="typeShow" placeholder="请选择类别" @click="typeShow = true" />
					<u-select :list="typeList" v-model="typeShow" @confirm="typeConfirm"></u-select>
				</u-form-item> -->

				<u-form-item class="form-item" required label="代表" v-if="$sysBtns('tian_add_xuanren')">
					<u-input v-model="leaderName" type="select" :select-open="leaderShow" placeholder="请选择代表" @click="leaderShow = true" />
					<select-tree ref="leaderTree" :show="leaderShow" :range="leaderList" :selected="leaderStr" :multiple="false" :selectParent="false" @confirm="treeConfirm($event, 'leader')" @cancel="treeCancel($event, 'leader')"></select-tree>
				</u-form-item>
				<u-form-item class="form-item" label="代表" v-else>{{ form.leaderName }}</u-form-item>

				<u-form-item class="form-item" required label="联系电话" prop="leaderPhone"><u-input v-model="form.leaderPhone" type="text" placeholder="请输入手机号" /></u-form-item>
				<!-- <u-form-item class="form-item" required label="邮政编码" prop="postcode"><u-input v-model="form.postcode" type="text" placeholder="请输入邮政编码" /></u-form-item> -->
				<u-form-item class="form-item" required label="通讯地址" prop="leaderAddress"><u-input v-model="form.leaderAddress" type="text" placeholder="请输入通讯地址" /></u-form-item>

				<u-form-item class="form-item" label="附议代表">
					<u-input v-model="lmName" type="select" :select-open="lmShow" placeholder="请选择附议代表" @click="lmShow = true" />
					<select-tree ref="lmTree" :show="lmShow" :range="lmList" :selected="lmStr" @confirm="treeConfirm($event, 'lm')" @cancel="treeCancel($event, 'lm')"></select-tree>
				</u-form-item>

				<uni-view class="title-blod">如有以下情况，请代表打勾具体注明：</uni-view>

				<u-form-item class="form-item" label="此建议有代表通过以下方式形成" label-position="top">
					<u-radio-group v-model="fromWay" input-align="left" :key="fromWay">
						<u-radio v-for="(item, index) in fromWayList" :key="index" :name="item.name">{{ item.value }}</u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item class="form-item" label="建议内容属于多年多次提出、尚未解决事项" label-position="top">
					<u-radio-group v-model="manyYear" input-align="left" :key="manyYear">
						<u-radio v-for="(item, index) in manyYearList" :key="index" :name="item.name">{{ item.value }}</u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item class="form-item" label="希望在办理过程中加强与代表联系沟通" label-position="top">
					<view class="input-left"><u-switch v-model="strongLink"></u-switch></view>
				</u-form-item>

				<u-form-item class="form-item" label="此建议请在工作中研究参考不需要书面答复" label-position="top">
					<view class="input-left"><u-switch v-model="noReply"></u-switch></view>
				</u-form-item>

				<u-form-item class="form-item" label="其他需要说明的情况" label-position="top"><u-input input-align="left" v-model="form.otherExplain" type="textarea" placeholder="请输入" :clearable="false" :height="320" :maxlength="-1" /></u-form-item>

				<u-form-item class="form-item" label="处理意见" label-position="top"><u-input input-align="left" v-model="form.checkClyj" type="textarea" placeholder="请输入" :clearable="false" :height="320" :maxlength="-1" /></u-form-item>
				<u-form-item class="form-item" label="处理时间"><date-time-picker placeholder="请选择处理时间" fields="day" :defaultValue="form.checkClyjTime" @change="timeChange($event, 'checkClyjTime')"></date-time-picker></u-form-item>

				<view class="title-text">
					注意事项：
					<br />
					1.一事一件。请用蓝黑或碳素钢笔填写，第一页请勿粘贴，其他页如有粘附，请用 A4纸。
					<br />
					2.“编号”、“类别”、“处理意见”栏，代表请勿填写。
					<br />
					3.两人以上代表提出建议，首页只填写领衔代表信息，其他代表信息在“联名附议代表签名附页”上填写。
				</view>
				<u-form-item class="form-item" label="收到时间"><date-time-picker placeholder="请选择收到时间" fields="day" :defaultValue="form.receiveDate" @change="timeChange($event, 'receiveDate')"></date-time-picker></u-form-item>
				<u-form-item class="form-item" required label="建议正文" label-position="top" prop="background">
					<u-input input-align="left" v-model="form.background" type="textarea" placeholder="请输入建议正文" @focus="ocr('background')" :clearable="false" :height="320" :maxlength="-1" />
				</u-form-item>

				<!-- <view class="ocr-box">
						<view class="ocr" @click="ocrTo('image', ocrKey)">
							<image src="/static/img/icon_90.png" mode="widthFix"></image>
							<view>图片识别</view>
						</view>
						<view class="ocr" @click="ocrTo('audio', ocrKey)">
							<image src="/static/img/icon_91.png" mode="widthFix"></image>
							<view>文字识别</view>
						</view>
					</view> -->

				<u-form-item class="form-item" label=" " label-position="top"><uni-file-upload :type="['all', 'image', 'audio']" :limit="10"></uni-file-upload></u-form-item>
			</u-form>
		</view>

		<view class="fiexd-btm">
			<view class="flex-box">
				<u-button class="form-btn" type="error" @click="confirm">提交</u-button>
				<u-button class="form-btn" type="success" @click="spare">草稿</u-button>
			</view>
		</view>
	</view>
</template>

<script>
import uniFileUpload from '@/components/uni-all-uploader.vue';
import dateTimePicker from '@/components/uni-datetime-picker';
import selectTree from '@/components/uni-select-tree.vue';
import { mapState } from 'vuex';
export default {
	components: {
		dateTimePicker,
		uniFileUpload,
		selectTree
	},
	data() {
		return {
			id: '',
			title: '提交建议',
			navItem: 1,
			ocrKey: 'background',
			commitFlag: true,
			dept: '',
			timer: '',
			disabled: false,

			strongLink: false,
			noReply: false,

			type: '',
			typeShow: false,
			typeList: [],

			fromWay: '',
			fromWayList: [
				{
					name: '1',
					value: '专题调研'
				},
				{
					name: '2',
					value: '视察'
				},
				{
					name: '3',
					value: '座谈、走访形式'
				}
			],

			manyYear: '',
			manyYearList: [
				{
					name: '1',
					value: '2年'
				},
				{
					name: '2',
					value: '3年'
				},
				{
					name: '3',
					value: '3年以上'
				}
			],

			lmIds: [],
			lmName: '',
			lmShow: false,
			lmList: [],
			lmStr: '',

			leaderIds: [],
			leaderName: '',
			leaderShow: false,
			leaderList: [],
			leaderStr: '',

			form: {
				id: '',
				no: '',
				jieci: '',
				title: '',
				type: '',
				kind: '3',
				postcode: '',
				leader: '',
				leaderName: '',
				leaderPhone: '',
				leaderAddress: '',
				receiveDate: '',
				checkClyjTime: '',
				fromWay: '',
				manyYear: '',
				strongLink: '',
				noReply: '',
				nodeStatus: '1',
				suggestion: '',
				cause: '',
				content: '',
				background: '',
				otherExplain: '',
				checkClyj: ''
			},
			rules: {
				title: [
					{
						required: true,
						message: '请输入标题',
						trigger: 'change'
					}
				],
				type: [
					{
						required: true,
						message: '请选择类别',
						trigger: 'change'
					}
				],
				postcode: [
					{
						required: true,
						message: '请输入邮编',
						trigger: 'change'
					}
				],
				leader: [
					{
						required: true,
						message: '请输入代表',
						trigger: 'change'
					}
				],
				leaderPhone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: ['change']
					},
					{
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change']
					}
				],
				leaderAddress: [
					{
						required: true,
						message: '请输入通讯地址',
						trigger: 'change'
					}
				],
				background: [
					{
						required: true,
						message: '请输入建议正文',
						trigger: 'change'
					}
				]
			}
		};
	},
	onLoad(option) {
		this.loadLogin();
		this.$store.commit('filePush', []);

		this.loadDict('motion_type', 'typeList');
		this.loadTeam('weiyuan, changwei');
		if (option && option.id) {
			this.id = option.id;
			if (option.type == 'clue') {
				this.clueData();
			} else if (option.type == 'cw') {
				this.cwData();
			} else {
				this.title = '修改建议';
				this.spareData();
			}
		} else {
			this.loadInfo(this.userId);
		}

		uni.setNavigationBarTitle({
			title: this.title
		});
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	onUnload() {
		this.$store.commit('filePush', []);
	},
	computed: {
		...mapState(['userInfo', 'fileList'])
	},
	methods: {
		loadLogin() {
			if (this.userInfo.Authorization) {
				this.clientCode = this.userInfo.sysUser.clientCode;
				this.userId = this.userInfo.sysUser.id;
				this.dept = this.userInfo.deptName;

				let time = this.$writeCurrentDate();

				this.form.createBy = this.userInfo.sysUser.id;
				this.form.jieci = this.userInfo.jieCi.pName + this.userInfo.jieCi.name;
				this.form.checkClyjTime = time.year + '-' + time.month + '-' + time.date;
				this.form.receiveDate = time.year + '-' + time.month + '-' + time.date;
			} else {
				this.$logout();
			}
		},
		selectShow(e) {
			if (this.disabled) {
				return false;
			}
			this[e] = true;
		},
		treeConfirm(e, type) {
			if (!e || e.length == 0) {
				this[type + 'Show'] = false;
				this[type + 'Name'] = '';
				this[type + 'Ids'] = [];
				return false;
			}
			if (type == 'leader') {
				this[type + 'Ids'] = [e[0].id];
				this.leaderName = e[0].name;
				this.loadInfo(e[0].id);
			} else {
				this[type + 'Ids'] = [];
				let names = [];
				let i = 0;
				e.forEach((item) => {
					this[type + 'Ids'].push(item.id);
					if (i < 2) {
						names.push(item.name);
						i++;
					}
				});
				this[type + 'Name'] = names.join(',') + '等' + e.length + '人';
			}
			this[type + 'Show'] = false;
		},
		treeCancel(e, type) {
			this[type + 'Show'] = false;
		},
		timeChange({ date, dt }, idx) {
			this.form[idx] = date.year + '-' + date.month2 + '-' + date.day2;
		},
		typeConfirm(e) {
			this.type = e[0].label;
			this.form.type = e[0].value;
		},
		loadDict(type, list) {
			this.$request('/system/sys-dict/dictList', {
				clientCode: this.clientCode,
				sysDict: {
					dictType: type
				}
			}).then((res) => {
				if (!res.data) {
					return false;
				}
				this[list] = [];
				res.data.forEach((item) => {
					this[list].push({
						value: item.dictValue,
						label: item.dictName
					});
				});
			});
		},
		clueData() {
			this.$request('/question/masses/query/' + this.id, {
				id: this.id,
				userId: this.userId
			}).then((res) => {
				if (!res.data) {
					return false;
				}
				// Object.assign(this.form, res.data.masses);
				this.form.title = res.data.masses.title;
				this.$store.commit('filePush', res.data.fileList);
				let obj = {
					hasLevel: '1',
					id: res.data.masses.userId,
					name: res.data.masses.userName
				};
				this.treeConfirm([obj], 'leader');

				let regx = /<[^>]*>|<\/[^>]*>/gm;
				if (res.data.masses.content) {
					this.form.background = res.data.masses.content.replace(regx, '');
				}
			});
		},
		cwData() {
			this.$request('/question/cw/query/' + this.id, {
				id: this.id,
				userId: this.userId
			}).then((res) => {
				if (!res.data) {
					return false;
				}
				// Object.assign(this.form, res.data.cw);
				this.form.title = res.data.cw.title;
				this.$store.commit('filePush', res.data.fileList);
				let obj = {
					hasLevel: '1',
					id: res.data.cw.userId,
					name: res.data.cw.userName
				};
				// this.treeConfirm([obj], 'leader');

				let regx = /<[^>]*>|<\/[^>]*>/gm;
				if (res.data.cw.content) {
					this.form.background = res.data.cw.content.replace(regx, '');
				}
			});
		},
		spareData() {
			this.joinList();
			let data = {
				id: this.id,
				currentUserId: this.userId
			};
			this.$request('/motion/query', data, {
				load: true
			}).then((res) => {
				// Object.assign(this.form, res.data.motion);
				Object.keys(this.form).forEach((key) => (this.form[key] = res.data.motion[key]));
				this.$store.commit('filePush', res.data.fileList);
				this.form.jieci = res.data.motion.jieName + res.data.motion.ciName;
				this.form.postcode = res.data.leaderInfo.postcode;

				this.leaderName = this.form.leaderName || '';
				this.leaderStr = this.form.leader || '';
				this.form.nodeStatus = '1';
				this.commitFlag = true;

				let regx = /<[^>]*>|<\/[^>]*>/gm;
				this.fromWay = this.form.fromWay;
				this.manyYear = this.form.manyYear;
				this.strongLink = this.form.strongLink == '1' ? true : false;
				this.noReply = this.form.noReply == '1' ? true : false;

				if (this.form.background) {
					this.form.background = this.form.background
						.replace(regx, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '');
				}
				if (this.form.content) {
					this.form.content = this.form.content
						.replace(regx, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '');
				}
				if (this.form.cause) {
					this.form.cause = this.form.cause
						.replace(regx, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '');
				}
				if (this.form.suggestion) {
					this.form.suggestion = this.form.suggestion
						.replace(regx, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '')
						.replace(/\n/i, '');
				}
				this.typeList.forEach((item) => {
					if (this.form.type == item.value) {
						this.type = item.label;
					}
				});
				this.fromWayList.forEach((item) => {
					if (this.form.fromWay == item.name) {
						this.fromWay = item.name;
					}
				});
				this.manyYearList.forEach((item) => {
					if (this.form.manyYear == item.name) {
						this.manyYear = item.name;
					}
				});
			});
		},
		loadTeam(type) {
			this.$request('/system/sys-user/team_users', {
				clientCode: this.clientCode,
				currentUserId: this.userId,
				dictType: 'jiebie',
				roleCodes: type,
				teamType: '2'
			}).then((res) => {
				this.lmList = res.data;
				this.leaderList = res.data;
			});
		},
		joinList() {
			this.$request('/motion/jointlyers/list', {
				clientCode: this.clientCode,
				motionJointlyers: { motionId: this.id, signFlag: '' }
			}).then((res) => {
				this.lmIds = [];
				let names = [];
				let i = 0;
				res.data.records.forEach((item) => {
					this.lmIds.push(item.userId);
					if (i < 2) {
						names.push(item.userName);
						i++;
					}
				});
				this.lmStr = this.lmIds.join(',');
				this.lmName = names.join(',') + '等' + this.lmIds.length + '人';
			});
		},
		loadInfo(userId) {
			this.$request('/system/user-info/queryInfoByUserId?id=' + userId, {
				id: userId
			}).then((res) => {
				if (!res.data) {
					return false;
				}
				this.form.leader = res.data.sysUserId;
				this.form.leaderName = res.data.name;
				this.form.leaderPhone = res.data.phoneNumber;
				this.form.leaderAddress = res.data.address;
				this.form.postcode = res.data.postcode;

				this.leaderName = this.form.leaderName || '';
				this.leaderStr = this.form.leader || '';
			});
		},
		onEditorReady(edit) {
			this.$refs.editor
				.context((res) => {
					this[edit] = res.context;
				})
				.exec();
		},
		spare() {
			this.commitFlag = false;
			this.form.nodeStatus = '0';
			this.confirm();
		},
		ocr(key) {
			this.ocrKey = key;
		},
		ocrTo(e, key) {
			this.ocrKey = key;
			uni.navigateTo({
				url: '/pagesB/ocr/index?ocrKey=' + this.ocrKey + '&type=' + e
			});
		},
		inputHandler(key) {
			this.form[key] = this.form[key];
		},
		confirm() {
			this.$refs.uForm.validate((valid) => {
				if (!valid) {
					return false;
				} else {
					if (!this.form.leader) {
						this.$msg('请选择代表');
						return false;
					}
					if (this.id) {
						this.form.motionClueId = this.id;
					}
					this.form.clientCode = this.clientCode;
					this.form.fromWay = this.fromWay;
					this.form.manyYear = this.manyYear;
					this.form.strongLink = this.strongLink ? '1' : '0';
					this.form.noReply = this.noReply ? '1' : '0';

					let motion = { ...this.form };

					let reg = /^(关于).*(建议)$/g;
					if (!reg.test(motion.title)) {
						motion.title = '关于' + motion.title + '的建议';
					}

					if (this.form.background) {
						motion.background = `<p>${this.form.background}</p>`;
					}
					if (this.form.content) {
						motion.content = `<p>${this.form.content}</p>`;
					}
					if (this.form.cause) {
						motion.cause = `<p>${this.form.cause}</p>`;
					}
					if (this.form.suggestion) {
						motion.suggestion = `<p>${this.form.suggestion}</p>`;
					}

					let data = {};
					data = {
						motionClue: this.motionClue,
						motion: motion,
						fileList: this.fileList,
						jointlyers: this.lmIds.join(','),
						commitFlag: this.commitFlag
					};

					this.$request('/motion/add', data, {
						load: true
					}).then((res) => {
						this.$msg(res.msg);
						setTimeout(() => {
							let pre = this.$prePage();
							if (pre && pre.proposalChange) {
								pre.proposalChange(res.data);
							} else if (pre && pre.loadData) {
								pre.loadData('refresh');
							}
							if (pre && pre.loadAll) {
								pre.loadAll();
							}
							uni.navigateBack();
						}, 500);
					});
				}
			});
		}
	}
};
</script>

<style lang="scss">
.detail-view {
	background-color: #fff;
}

.form-box {
	.form-item {
		@include mp-flex;
		border-bottom: 20rpx solid $u-border-color;
	}

	.input-text {
		float: right;
		margin-right: 30rpx;
		font-size: 12px;
	}

	.input-left {
		display: flex;
		align-items: center;
		width: 100%;
		height: 62rpx;
		text-align: left;
	}

	.title-tip {
		display: block;
		padding: 30rpx;
		font-size: 15px;
		color: rgb(255, 113, 0);
		text-align: center;
		border-bottom: 20rpx solid $u-border-color;
	}

	.title-blod {
		display: block;
		padding: 20rpx 30rpx;
		font-size: 17px;
		font-weight: bold;
		border-bottom: 20rpx solid $u-border-color;
	}

	.title-text {
		display: block;
		padding: 20rpx 30rpx;
		font-size: 16px;
		border-bottom: 20rpx solid $u-border-color;
		background-color: $u-border-color;
	}
}

.fiexd-btm {
	position: static;
	padding: 30rpx;

	.form-btn {
		width: 100%;
	}

	.flex-box .form-btn {
		width: 48%;
	}
}
</style>
